package com.lpb.spring.lpbspring.getway.model;



import com.lpb.spring.lpbspring.getway.anno.Unescape;

import java.lang.reflect.Field;

import static com.lpb.spring.lpbspring.getway.util.ClassUtils.getDeclaredFields;
import static com.lpb.spring.lpbspring.getway.util.ClassUtils.isAnnotationPresent;


/**
 * cher on 2017/11/15.
 */
public abstract class Defense {
    public void escape() throws Exception {
        if(isAnnotationPresent(this.getClass(), Unescape.class)) {
            return;
        }
        for(Field field : getDeclaredFields(this.getClass())) {
            if(field.isAnnotationPresent(Unescape.class) || field.getType() != String.class) {
                continue;
            }
            field.setAccessible(true);
            Object value = field.get(this);
            if(value == null) {
                continue;
            }
            field.set(this, XssDefense.htmlEncode(value.toString()));
            field.setAccessible(false);
        }
    }
}
